package com.aabte.lota.auth.account.service;

import com.aabte.lota.auth.account.bean.query.UserQuery;
import com.aabte.lota.auth.account.entity.User;
import com.aabte.lota.auth.account.exception.UserAlreadyExistsException;
import com.aabte.lota.auth.account.exception.UserNotFoundException;
import com.aabte.lota.auth.account.mapper.UserMapper;
import com.aabte.lota.auth.auth.shiro.PasswordBO;
import com.aabte.lota.auth.auth.shiro.PasswordUtils;
import com.aabte.lota.auth.auth.shiro.configure.ShiroRealmConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/29
 */
@Service
public class UserService {

  @Resource private UserMapper userMapper;

  public List<User> list() {
    return userMapper.selectList(new QueryWrapper<>());
  }

  public User queryUserByUsername(String username) throws UserNotFoundException {
    Map<String, Object> param = new HashMap<>(1);
    param.put("username", username);
    List<User> users = userMapper.selectByMap(param);
    if (null == users || users.size() == 0) {
      throw new UserNotFoundException("username: " + username);
    }
    return users.get(0);
  }

  public Long add(UserQuery userQuery) {
    String username = userQuery.getUsername();
    User userFromDb = queryUserByUsername(username);
    if (null != userFromDb) {
      throw new UserAlreadyExistsException();
    }

    PasswordBO passwordBO =
        PasswordUtils.encryptPassword(userQuery.getPassword(), ShiroRealmConfig.HASH_ITERATIONS);
    User user =
        User.builder()
            .username(userQuery.getUsername())
            .password(passwordBO.getCipherText())
            .salt(passwordBO.getSalt())
            .build();
    int insert = userMapper.insert(user);
    return (long) insert;
  }
}
